package cn.com.ddapp.ddm.fragment.base.limittime;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.adapter.NewGoodsAdapter;
import cn.com.ddapp.ddm.adapter.NewGoodsOutAdapter;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.ActivityBean;
import cn.com.ddapp.ddm.bean.HomeBean;
import cn.com.ddapp.ddm.fragment.base.BaseFragment;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.ui.CommidContentActivity;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.util.CountDownLimitTimer;
import cn.com.ddapp.ddm.util.NetUtils;
import cn.com.ddapp.ddm.util.TLog;
import cn.com.ddapp.ddm.widget.pulltorefresh.PullToRefreshLayout;
import cn.com.ddapp.ddm.widget.pulltorefresh.pullableview.PullableListView;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/8/23 0023.
 */
public class TimeOneFragment extends BaseFragment {
    @BindView(R.id.error_layout)
    EmptyLayout mEmptyLayout;
    @BindView(R.id.img_error_layout)
    ImageView img_error_layout;
    @BindView(R.id.limittime)
    CountDownLimitTimer limittime;
    @BindView(R.id.limit_ing)
    TextView limit_ing;
    @BindView(R.id.limit_out)
    TextView limit_out;
    @BindView(R.id.share_refresh)
    PullToRefreshLayout share_refresh;
    @BindView(R.id.definiteList)
    PullableListView definiteList;
    private ActivityBean activityBean;
    private List<ActivityBean.PromotionListBean> promotionListBeen;
    private int h,m;
    private String actid,preH,preM,endH,endM;
    private String starttime;
    private String endtime;
    private String now;
    private boolean flag=false;
    private int startInt=0;

    @Override
    protected String getFragmentTag() {
        return null;
    }

    private NewGoodsOutAdapter outAdapter;
    private NewGoodsAdapter newGoodsAdapter;
    SimpleDateFormat hdf=new SimpleDateFormat("HH");
    SimpleDateFormat mdf=new SimpleDateFormat("mm");
    String hTime=hdf.format(new Date());
    String mTime=mdf.format(new Date());
    @Override
    protected void initData() {
        try {

        actid = getArguments().getString("actid");
        starttime = getArguments().getString("starttime");
        endtime = getArguments().getString("endtime");
        String times[]=endtime.split(":");
        preH=times[0];   //离结束的小时数
        preM=times[1];   //离结束的分钟数

        String endTimes[]=starttime.split(":");
        endH=endTimes[0];   //离开始的小时数
        endM=endTimes[1];    //离开始的分钟数


        now = getArguments().getString("now");

            requestData(false);
            share_refresh.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                    startInt=0;
                    requestData(false);
                    share_refresh.refreshFinish(PullToRefreshLayout.SUCCEED);
                }

                @Override
                public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                    startInt++;
                    requestData(true);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * @param flag 判断上拉还是下拉
     * 获取网络数据
     */
    private void requestData(final boolean flag) {
        if (!NetUtils.isConnected(getContext())) {
            Toast.makeText(getContext(), "请检查你的网络", Toast.LENGTH_SHORT).show();
        } else {
            mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            OkUtilCallback okUtilCallback = new OkUtilCallback(mEmptyLayout) {
                @Override
                public void onMyResponse(String response, int id) {
                    TLog.log(getFragmentTag(), response);
                    Log.e("TAG", "onMyResponse: " + response);
                    activityBean = gson.fromJson(response, ActivityBean.class);

                        Log.i("aaa","--flag--"+startInt);
                        if (flag) {
                                promotionListBeen = activityBean.getPromotionList();
                                if(promotionListBeen.size()==0){
                                    share_refresh.loadmoreFinish(PullToRefreshLayout.NODATA);
                                    return;
                                }
                            promotionListBeen.addAll(activityBean.getPromotionList());
                            switch (gettime(starttime + ":00", endtime + ":59", now)) {
                                case 0: //未开抢
                                    outAdapter.notifyDataSetChanged();
                                    break;
                                case 1: //抢购中
                                    newGoodsAdapter.notifyDataSetChanged();
                                    break;
                                case 2: //已结束
                                    outAdapter.notifyDataSetChanged();
                                    break;
                            }

                        }else{
                            if ((!AppConfig.RESULT_OK.equalsIgnoreCase(activityBean.getResult()))) {
                                BaseApplication.getIntstance().showToast(activityBean.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                                mEmptyLayout.setErrorType(EmptyLayout.NODATA_ENABLE_CLICK);
                            } else if (activityBean.getResult().equals("OK") && activityBean.getPromotionList().size() == 0) {
                                mEmptyLayout.setErrorType(EmptyLayout.NODATA);
                            } else if ((AppConfig.RESULT_OK.equalsIgnoreCase(activityBean.getResult()))) {

                            promotionListBeen = activityBean.getPromotionList();
                            startInt=promotionListBeen.size()-1;
                            switch (gettime(starttime + ":00", endtime + ":59", now)) {
                                case 0: //未开抢
                                    outAdapter=new NewGoodsOutAdapter(getContext(), promotionListBeen);
                                    definiteList.setAdapter(outAdapter);
                                    limit_out.setVisibility(View.GONE);
                                    limit_ing.setVisibility(View.VISIBLE);
                                    limittime.setVisibility(View.VISIBLE);
                                    h=Integer.parseInt(endH)-Integer.parseInt(hTime)-1;
                                    m=59-Integer.parseInt(mTime);
                                    limittime.setTime(h,m,59);
                                    limittime.start();
                                    break;
                                case 1: //抢购中
                                    newGoodsAdapter=new NewGoodsAdapter(getContext(), promotionListBeen);
                                    definiteList.setAdapter(newGoodsAdapter);
                                    limit_out.setVisibility(View.GONE);
                                    limit_ing.setVisibility(View.VISIBLE);
                                    limittime.setVisibility(View.VISIBLE);
                                    h=Integer.parseInt(preH)-Integer.parseInt(hTime);
                                    m=Integer.parseInt(preM)-Integer.parseInt(mTime);
                                    limittime.setTime(h,m,59);
                                    limittime.start();
                                    definiteList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                            Intent intent = new Intent(getContext(), CommidContentActivity.class);
                                            int id = promotionListBeen.get(i).getId();
                                            intent.putExtra("type","id");
                                            intent.putExtra("id", String.valueOf(id));
                                            startActivity(intent);
                                        }
                                    });
                                    break;
                                case 2: //已结束
                                    outAdapter=new NewGoodsOutAdapter(getContext(), promotionListBeen);
                                    definiteList.setAdapter(outAdapter);
                                    limit_out.setVisibility(View.VISIBLE);
                                    limit_ing.setVisibility(View.GONE);
                                    limittime.setVisibility(View.GONE);
                                    break;
                            }
                        }

                    }
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    super.onError(call, e, id);
                    mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                }
            };
            OKUtilAPI.get(OKUtilAPI.HUOCommid,"id=" + actid+"&st="+startInt, okUtilCallback);
        }
    }


    public static int gettime(String star, String end, String sys) {
        java.text.DateFormat df = new java.text.SimpleDateFormat("HH:mm:ss");
        java.util.Calendar c1 = java.util.Calendar.getInstance();
        java.util.Calendar c2 = java.util.Calendar.getInstance();
        java.util.Calendar c3 = java.util.Calendar.getInstance();
        try {
            c1.setTime(df.parse(star));
            c2.setTime(df.parse(sys));
            c3.setTime(df.parse(end));
        } catch (java.text.ParseException e) {
            System.err.println("时间格式不正确");
        }
        int result = -1;
        if (c1.compareTo(c2) > 0) {
            result = 0;
        } else if (c1.compareTo(c2) <= 0 && c2.compareTo(c3) <= 0) {
            result = 1;
        } else if (c2.compareTo(c3) > 0) {
            result = 2;
        }
        return result;
    }

    private void startRun() {
        limittime.setTime(1,15,33);
        limittime.start();
    }
    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        img_error_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initData();
            }
        });
        startInt=0;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_definite_goods;
    }


}
